package com.syni.mdd.yhd.common.all.service;

import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsReportErrorDao;
import com.syni.mdd.yhd.common.all.entity.BmsBusiness;
import com.syni.mdd.yhd.common.all.entity.BmsReportError;
import com.syni.mdd.yhd.common.all.listen.businessReportError.ReportErrorEvent;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @className BmsUserOperationLogService
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
public class BmsReportErrorService extends BaseService<BmsReportError, Integer> {

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsReportErrorDao bmsReportErrorDao;

    @Override
    public BmsReportErrorDao getBaseDao() {
        return bmsReportErrorDao;
    }

    public Map<String,Object> recordReportError(Integer businessId,Integer userId,
                                            Integer errorType, String errorContent,Integer createWay) {
        Optional<BmsBusiness> bmsBusinessOptional = bmsBusinessService.getBaseDao().findById(businessId);
        if(!bmsBusinessOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"店铺不存在");
        }
        BmsBusiness business = bmsBusinessOptional.get();
        BmsReportError bmsReportError = new BmsReportError();
        bmsReportError.setBmsBusinessId(businessId);
        bmsReportError.setBmsUserId(userId);
        bmsReportError.setNewTime(new Date());
        bmsReportError.setErrorType(errorType);
        bmsReportError.setCreateWay(createWay);
        String[] errorContents = errorContent.split("_");
        if(errorContents.length > 0){
            List<String> errContents = Arrays.asList(errorContents);
            bmsReportError.setErrorContent(StringUtils.join(errContents,"_"));
        }else {
            bmsReportError.setErrorContent("");
        }
        bmsReportError.setVendorName(business.getVendorName());
        bmsReportErrorDao.save(bmsReportError);
        //发送消息
        //BmsCommonService.getApplicationContext().publishEvent(new ReportErrorEvent("businessReportError",bmsReportError));
        return ResultMapHelper.success();
    }
}
